package org.example.java.util.concurrency.exception;

import static java.lang.System.out;

/**
 * 如果当前线程不是此对象监视器的所有者
 * User: ZhangJuntao
 * Date: 14-1-9
 * Time: 上午9:46
 */
public class IllegalMonitorStateExceptionTest {
  public static void main(String[] args) throws InterruptedException {
    testSynchronized();
    duplicatedStart();
  }

  // 如果线程已经启动
  private static void duplicatedStart() {
    ThreadA a = new ThreadA();
    Thread currentThread = Thread.currentThread();
    System.out.println(a.toString());
    System.out.println(currentThread.toString());
    a.start();
//    a.start();  //抛IllegalMonitorStateException
//    currentThread.start();//抛IllegalMonitorStateException
  }

  // 操作的线程非synchronized监视的线程
  private static void testSynchronized() throws InterruptedException {
    Thread currentThread = Thread.currentThread();
    ThreadB b = new ThreadB();
    System.out.println(currentThread);
    b.start();
    synchronized (currentThread) { //抛IllegalMonitorStateException
//    synchronized (b) {
      try {
        System.out.println("Waiting for b to complete...");
        b.wait();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      System.out.println("Total is: " + b.total);
    }

  }

  public static class ThreadA extends Thread {
    public void run() {
      for (int i = 0; i < 10; i++) {
        out.print(i + " ");
      }
      out.println();
    }
  }

  public static class ThreadB extends Thread {
    int total;

    @Override
    public void run() {
      synchronized (this) {
        for (int i = 0; i < 100; i++) {
          total += i;
        }
        notify();
      }
    }
  }
}
